/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/8/25 23:32
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.controller;

import com.hyacinth.constant.GlobalConstant;
import com.hyacinth.entity.User;
import com.hyacinth.security.SpringSessionRegistry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Slf4j
@Controller
public class HomeController {

    private final SpringSessionRegistry sessionRegistry;

    @Autowired
    public HomeController(SpringSessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    @GetMapping("index")
    public String home() {
        return "index";
    }

    @GetMapping({"/", "login"})
    public String login() {
        return "login";
    }

    @PostMapping("/j_login")
    @ResponseBody
    public String login(String username, String password) {
        log.info("login username = {}, password = {}", username, password);
        return "SUCCESS";
    }

    @PostMapping("hello")
    @ResponseBody
    public String hello(String tip) {
        log.info("hello post req ===== " + tip);
        return tip;
    }

    @GetMapping("hello")
    @ResponseBody
    public String hello() {
        return "Hello Spring Security";
    }

    /**
     * 退出系统访问链接
     */
    @RequestMapping(value = "/mylogout")
    public String myLogout() {
        Object userDetails = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (null != userDetails && !GlobalConstant.ANONYMOUS_USER.equals(userDetails)) {
            User authUser = (User) userDetails;
            List<SessionInformation> sis = sessionRegistry.getAllSessions(authUser, false);
            if (sis != null) {
                for (SessionInformation si : sis) {
                    si.expireNow();
                    if (si.isExpired()) {
                        this.sessionRegistry.removeSessionInformation(si.getSessionId());
                    }
                }
            }
            log.info("用户（" + authUser.getName() + "）登出系统！");
            return "redirect:/logout";
        } else {
            return "/login";
        }
    }
}
